package com.epfresh.views.dialog;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.CategoryListAdapter;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.bean.Category;
import com.epfresh.bean.GoodsParameters;
import com.epfresh.bean.ProductCategoryNames;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.tag.FlowLayout;
import com.epfresh.views.tag.TagAdapter;
import com.epfresh.views.tag.TagFlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 16-7-8.
 */
public class ProductCategoryDialog extends BaseDialogView {

    private ListView lv;

    private CategoryListAdapter adapter;

    private TagFlowLayout tagFlowLayout;

    private List<Category> list = new ArrayList<>();
    private List<ProductCategoryNames> listVarieties = new ArrayList<>();

    private TagAdapter<ProductCategoryNames> tagAdapter;

    private String nameId;
    private String parentId;
    private String grandParentId;
    private String marketId;

    int tagW = -1;
    int tagAllW = -1;

    //记录上次选中数据
    GoodsParameters parameters;
    OnFilterClickListener onFilterClickListener;

    public GoodsParameters getParameters() {
        return parameters;
    }

    public void setParameters(GoodsParameters parameters) {
        this.parameters = parameters;
    }

    public OnFilterClickListener getOnFilterClickListener() {
        return onFilterClickListener;
    }

    public void setOnFilterClickListener(OnFilterClickListener onFilterClickListener) {
        this.onFilterClickListener = onFilterClickListener;
    }

    public String getMarketId() {
        return marketId;
    }

    public void setMarketId(String marketId) {
        this.marketId = marketId;
    }

    public ProductCategoryDialog(Context context) {
        super(context);
        init();

    }

    @Override
    public void initBefore() {
        setGravity(Gravity.RIGHT);
    }


    public View init() {


        View v = LayoutInflater.from(context).inflate(R.layout.dialog_category, contentContainer);
        contentContainer.setBackgroundColor(Color.WHITE);
        ViewGroup.LayoutParams lp0 = contentContainer.getLayoutParams();

        ViewGroup.LayoutParams lp = v.getLayoutParams();

        lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS * 4 / 5;
        lp0.width = lp.width;
        lp0.height = ViewGroup.LayoutParams.MATCH_PARENT;

        setCancelable(true);


        tagW = lp.width - LocalDisplay.dp2px(92) - LocalDisplay.dp2px(4) * 6;
        tagAllW = lp.width - LocalDisplay.dp2px(92) - LocalDisplay.dp2px(4) * 2;
        tagW /= 2;
        lv = (ListView) findViewById(R.id.lv);
        tagFlowLayout = (TagFlowLayout) findViewById(R.id.t_tag);

        adapter = new CategoryListAdapter(context, list);
        lv.setAdapter(adapter);

        adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Category category = list.get(position);
                String id1 = category.getId();
                List<ProductCategoryNames> names = category.getCategoryNames();

                if (grandParentId != null && !"".equals(grandParentId) && grandParentId.equals(id1)) {
                    if (names != null) {
                        for (int j = 0; j < names.size(); j++) {
                            ProductCategoryNames categoryNames = names.get(j);
                            if (categoryNames != null) {
                                String id2 = categoryNames.getId();
                                if (id2 != null && !"".equals(id2) && id2.equals(nameId)) {
                                    if (category != null) {
                                        category.setSelect(true);
                                        updateTag(names, j);
                                        return;
                                    }
                                }
                            }

                        }
                    }
                }
                updateTag(names, -1);
                if (position == 0) {

                    if (parameters == null) {
                        parameters = new GoodsParameters();
                    }
                    parameters.setCategoryId(null);
                    parameters.setNameId(null);
                    parameters.setGrandParentId(null);
                    parameters.setParentId(null);
                    parameters.setName("全部分类");

                    if (onFilterClickListener != null) {
                        onFilterClickListener.onFilter(parameters);
                    }
                    dismiss();
                }
            }
        });

        tagFlowLayout.setMaxSelectCount(1);
        tagAdapter = new TagAdapter<ProductCategoryNames>(listVarieties) {
            @Override
            public View getView(FlowLayout parent, int position, ProductCategoryNames categoryNamesVarieties) {

                if (categoryNamesVarieties.isTitle()) {
                    View v = LayoutInflater.from(context).inflate(R.layout.list_item_category_all,
                            parent, false);
                    ViewGroup.LayoutParams lp = v.getLayoutParams();
                    lp.width = tagAllW;
                    TextView tv = (TextView) v.findViewById(R.id.tv_title);
                    tv.setText(categoryNamesVarieties.getName());


                    return v;
                } else {
                    TextView tv = (TextView) LayoutInflater.from(context).inflate(R.layout.tag,
                            parent, false);
                    ViewGroup.LayoutParams lp = tv.getLayoutParams();
                    lp.width = tagW;
                    tv.setText(categoryNamesVarieties.getName());
                    if (categoryNamesVarieties.isEmpty()) {
                        tv.setVisibility(View.GONE);
                    } else {
                        tv.setVisibility(View.VISIBLE);
                    }
                    return tv;
                }
            }
        };
        tagFlowLayout.setAdapter(tagAdapter);


        tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                if (position < listVarieties.size()) {
                    tagAdapter.setSelectedList(position);
                    ProductCategoryNames categoryNames = listVarieties.get(position);
                    if (!categoryNames.isTitle() && !categoryNames.isEmpty()) {

                        if (parameters == null) {
                            parameters = new GoodsParameters();
                        }
                        parameters.setNameId(categoryNames.getId());
                        parameters.setCategoryId(null);
                        parameters.setName(categoryNames.getName());
                        parameters.setGrandParentId(categoryNames.getCategoryId());
                        parameters.setParentId(categoryNames.getProductCategoryId());

                    } else if (categoryNames.isTitle()) {
                        if (parameters == null) {
                            parameters = new GoodsParameters();
                        }
                        parameters.setCategoryId(categoryNames.getId());
                        parameters.setNameId(null);
                        parameters.setName(categoryNames.getName());
                        parameters.setGrandParentId(categoryNames.getCategoryId());
                        parameters.setParentId(categoryNames.getProductCategoryId());
                    }

                    if (onFilterClickListener != null) {
                        onFilterClickListener.onFilter(parameters);
                    }
                    dismiss();
                }
                return true;
            }
        });


        return v;
    }


    public void updateTag(List<ProductCategoryNames> list, int select) {
        listVarieties.clear();
        if (list != null) {
            listVarieties.addAll(list);
        }
        tagAdapter.setSelectedList(select);

    }

    public void updateTag() {
        if (parameters != null) {
            parentId = parameters.getParentId();
            grandParentId = parameters.getGrandParentId();
            nameId = parameters.getNameId();
        } else {
            parentId = null;
            nameId = null;
            grandParentId = null;
        }

        if (list.size() == 0){
            return;
        }
        Category category = list.get(0);
        int index = -1;
        List<ProductCategoryNames> names = null;
        if (category != null) {
            names = category.getCategoryNames();
        }
        for (int i = 0; i < list.size(); i++) {
            Category c = list.get(i);
            if (c != null && grandParentId != null && grandParentId.equals(c.getId())) {
                category = c;
                c.setSelect(true);

                names = c.getCategoryNames();

                if (names != null && parentId != null && nameId != null) {
                    for (int j = 0; j < names.size(); j++) {
                        ProductCategoryNames productCategoryNames = names.get(j);
                        if (parentId.equals(productCategoryNames.getProductCategoryId()) && nameId.equals(productCategoryNames.getId())) {
                            index = j;
                            break;
                        }
                    }
                }

            }
            if (index > -1) {
                break;
            }
        }

        Category c = new Category();
        c.setName("全部分类");
        list.add(0, c);
        if (category != null) {

            category.setSelect(true);
            updateTag(names, index);
        }


    }


    public void initStatus(List<Category> responseElement) {
        list.clear();
        list.addAll(responseElement);
        updateTag();
        adapter.notifyDataSetChanged();
    }

    public void updateCategory() {
        setOnErrorClickListener(onErrorClickListener);
        requestCategory(marketId, parameters != null ? parameters.getDeliveryTime() : null);
    }

    @Override
    public void dismiss() {
        list.clear();
        listVarieties.clear();
        adapter.notifyDataSetChanged();
        tagAdapter.notifyDataChanged();
        super.dismiss();
    }


    private OnRequestListener<List<Category>> onRequestListener = new OnRequestListener<List<Category>>() {
        @Override
        public List<Category> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<Category>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            showErrorView();
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            showErrorView();
        }

        @Override
        public void onStart(Object o) {
            showLoadView();
        }

        @Override
        public void onResponse(ResponseEntity<List<Category>> responseEntity, Object o) {


            List<Category> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                showContentView();
                initStatus(responseElement);
            } else {
                showErrorView();
            }


        }
    };

    public void requestCategory(String marketId, String deliveryTime) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_category_tree4purchaser);

        re.putParameter("marketId", marketId);
        re.putParameter("deliveryTime", deliveryTime);
        ((BaseActivity) context).request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_category_tree4purchaser, onRequestListener);
    }

    private View.OnClickListener onErrorClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            requestCategory(marketId, parameters != null ? parameters.getDeliveryTime() : null);
        }
    };
}
